package com.gasstation

import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Date

import com.gasstation.domain.GasUtil

class GasPurchasesController {

	static allowedMethods = [save: "POST", update: "POST"]

	def index = {
		redirect(action: "create", params: params)
	}

	def list = {
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		[gasPurchasesInstanceList: GasPurchases.list(params), gasPurchasesInstanceTotal: GasPurchases.count(), monthYear:new Date()]
	}
	def listAsPerMonth = {
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		def c = GasPurchases.createCriteria()
		Date month = params.monthYear
		if(month == null){
			month = new Date()
		}

		def gasList = c.list{between("transactionOn", GasUtil.getFirstDayOfMonth(month), GasUtil.getLastDayOfMonth(month))}
		render(view: "list", model: [gasPurchasesInstanceList:gasList, monthYear:month, gasPurchasesInstanceTotal: GasPurchases.count()])
	}

	def create = {
		Date transactionOn = null
		Object date = params.transactionOnStr
		DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy")
		if(date instanceof String){
			transactionOn = formatter.parse(date)
		}
		if(transactionOn == null){
			transactionOn = new Date()
		}
		transactionOn = GasUtil.getStartDate(transactionOn)
		def gasPurchasesInstance = GasPurchases.findByTransactionOnBetween(GasUtil.getPreviousDate(-1, transactionOn), GasUtil.getPreviousDate(0, transactionOn))
		if(gasPurchasesInstance == null){
			gasPurchasesInstance = new GasPurchases()
		}

		gasPurchasesInstance.properties = params
		return [gasPurchasesInstance: gasPurchasesInstance, transactionOnStr:formatter.format(transactionOn), transactionOn:transactionOn]
	}

	def save = {
		Date transactionOn = null
		Object date = params.transactionOnStr
		DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy")
		if(date instanceof String){
			transactionOn = formatter.parse(date)
		}
		if(transactionOn == null){
			transactionOn = new Date()
		}
		transactionOn = GasUtil.getStartDate(transactionOn)

		params.transactionOn= transactionOn
		def gasPurchasesInstance = GasPurchases.findByTransactionOnBetween(GasUtil.getPreviousDate(-1, transactionOn), GasUtil.getPreviousDate(0, transactionOn))
		if(gasPurchasesInstance == null){
			gasPurchasesInstance = new GasPurchases(params)
		}
		GasPurchases.withTransaction{ status ->
			try{
				if (gasPurchasesInstance.save(flush: true)) {
					flash.message = "${message(code: 'default.created.message', args: [message(code: 'gasPurchases.label', default: 'GasPurchases'), gasPurchasesInstance.id])}"
					session.regPurchasePricePerGallon = gasPurchasesInstance.regularPricePerGallon
					session.midPurchasePricePerGallon = gasPurchasesInstance.midGradePricePerGallon
					session.premiumPurchasePricePerGallon = gasPurchasesInstance.premiumPricePerGallon

					def inventoryRegularInstance = InventoryRegular.findByTransactionOnBetween(GasUtil.getPreviousDate(-1, transactionOn), GasUtil.getPreviousDate(0, transactionOn))
					if(inventoryRegularInstance == null){
						inventoryRegularInstance = new InventoryRegular(params)
					}else{
						String regNetGallons = params.regularNetGallons
						String regPriceGallons = params.regularPricePerGallon

						if(regNetGallons !=null && !"".equals(regNetGallons) && Double.parseDouble(regNetGallons) > 0){
							inventoryRegularInstance.regularPurchasedGallons = Double.parseDouble(regNetGallons)
						}
						if(regPriceGallons !=null && !"".equals(regPriceGallons) && Double.parseDouble(regPriceGallons) > 0){
							inventoryRegularInstance.regularPurchasedCost = Double.parseDouble(regNetGallons)*Double.parseDouble(regPriceGallons)
						}
					}
					GasUtil.saveInventoryRegular(inventoryRegularInstance)
					GasUtil.updateSubsequentInventoryRegular(inventoryRegularInstance, transactionOn)

					def inventoryMidGradeInstance = InventoryMidGrade.findByTransactionOnBetween(GasUtil.getPreviousDate(-1, transactionOn), GasUtil.getPreviousDate(0, transactionOn))
					if(inventoryMidGradeInstance == null){
						inventoryMidGradeInstance = new InventoryMidGrade(params)
					}else{
						String midNetGallons = params.midGradeNetGallons
						String midPriceGallons = params.midGradePricePerGallon

						if(midNetGallons !=null && !"".equals(midNetGallons) && Double.parseDouble(midNetGallons) > 0){
							inventoryMidGradeInstance.midGradePurchasedGallons = Double.parseDouble(midNetGallons)
						}
						if(midPriceGallons !=null && !"".equals(midPriceGallons) && Double.parseDouble(midPriceGallons) > 0){
							inventoryMidGradeInstance.midGradePurchasedCost = Double.parseDouble(midNetGallons)*Double.parseDouble(midPriceGallons)
						}
					}
					GasUtil.saveInventoryMidGrade(inventoryMidGradeInstance)
					GasUtil.updateSubsequentInventoryMidGrade(inventoryMidGradeInstance, transactionOn)

					def inventoryPremiumInstance = InventoryPremium.findByTransactionOnBetween(GasUtil.getPreviousDate(-1, transactionOn), GasUtil.getPreviousDate(0, transactionOn))
					if(inventoryPremiumInstance == null){
						inventoryPremiumInstance = new InventoryPremium(params)
					}else{
						String preNetGallons = params.premiumNetGallons
						String prePriceGallons = params.premiumPricePerGallon

						if(preNetGallons !=null && !"".equals(preNetGallons) && Double.parseDouble(preNetGallons) > 0){
							inventoryPremiumInstance.premiumPurchasedGallons = Double.parseDouble(preNetGallons)
						}
						if(prePriceGallons !=null && !"".equals(prePriceGallons) && Double.parseDouble(prePriceGallons) > 0){
							inventoryPremiumInstance.premiumPurchasedCost = Double.parseDouble(preNetGallons)*Double.parseDouble(prePriceGallons)
						}
					}
					GasUtil.saveInventoryPremium(inventoryPremiumInstance)
					GasUtil.updateSubsequentInventoryPremium(inventoryPremiumInstance, transactionOn)

					redirect(action: "listAsPerMonth")
				}
				else {
					render(view: "create", model: [gasPurchasesInstance: gasPurchasesInstance])
				}
			}catch(Exception e){
				e.printStackTrace()
				gasPurchasesInstance.errors.reject(e.getMessage())
				status.setRollbackOnly()
			}
		}
	}

	def show = {
		def gasPurchasesInstance = GasPurchases.get(params.id)
		if (!gasPurchasesInstance) {
			flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'gasPurchases.label', default: 'GasPurchases'), params.id])}"
			redirect(action: "list")
		}
		else {
			[gasPurchasesInstance: gasPurchasesInstance]
		}
	}

	def edit = {
		def gasPurchasesInstance = GasPurchases.get(Long.valueOf(params.id))
		if (!gasPurchasesInstance) {
			flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'gasPurchases.label', default: 'GasPurchases'), params.id])}"
			redirect(action: "listAsPerMonth")
		}
		else {
			return [gasPurchasesInstance: gasPurchasesInstance]
		}
	}

	def update = {
		def gasPurchasesInstance = GasPurchases.get(Long.valueOf(params.id))
		if (gasPurchasesInstance) {
			if (params.version) {
				def version = params.version.toLong()
				if (gasPurchasesInstance.version > version) {

					gasPurchasesInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [
						message(code: 'gasPurchases.label', default: 'GasPurchases')]
					as Object[], "Another user has updated this GasPurchases while you were editing")
					render(view: "edit", model: [gasPurchasesInstance: gasPurchasesInstance])
					return
				}
			}
			gasPurchasesInstance.properties = params
			if (!gasPurchasesInstance.hasErrors() && gasPurchasesInstance.save(flush: true)) {
				flash.message = "${message(code: 'default.updated.message', args: [message(code: 'gasPurchases.label', default: 'GasPurchases'), gasPurchasesInstance.id])}"
				redirect(action: "listAsPerMonth")
			}
			else {
				render(view: "edit", model: [gasPurchasesInstance: gasPurchasesInstance])
			}
		}
		else {
			flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'gasPurchases.label', default: 'GasPurchases'), params.id])}"
			redirect(action: "listAsPerMonth")
		}
	}

	def delete = {
		def gasPurchasesInstance = GasPurchases.get(Long.valueOf(params.id))
		if (gasPurchasesInstance) {
			try {
				gasPurchasesInstance.delete(flush: true)
				flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'gasPurchases.label', default: 'GasPurchases'), params.id])}"
				redirect(action: "listAsPerMonth")
			}
			catch (org.springframework.dao.DataIntegrityViolationException e) {
				flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'gasPurchases.label', default: 'GasPurchases'), params.id])}"
				redirect(action: "show", id: params.id)
			}
		}
		else {
			flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'gasPurchases.label', default: 'GasPurchases'), params.id])}"
			redirect(action: "listAsPerMonth")
		}
	}
}
